package com.gitee.generator.universal.datasource.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.sql.DataSource;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.hutool.db.meta.Column;
import cn.hutool.db.meta.MetaUtil;
import cn.hutool.db.meta.TableType;
import com.gitee.generator.universal.common.Constants;
import com.gitee.generator.universal.common.DataTypeEnum;
import com.gitee.generator.universal.domain.Project;
import com.gitee.generator.universal.domain.Table;
import com.gitee.generator.universal.domain.TableColumn;
import com.gitee.generator.universal.datasource.service.TableService;
import lombok.extern.slf4j.Slf4j;
/**
 * [表]Service
 * @date 2020-08-19 11:24
 * @author wsx
 */
@Slf4j
public class TableServiceImpl implements TableService {

    @Override
    public List<Table> listTablesWithColumns(Project cfg) {
        List<String> tableNameSet = new ArrayList<>();
        Map<String,Map<String,Object>> generateTables = Optional.ofNullable(cfg.getTables()).orElse(new HashMap<>(16));
        generateTables.forEach((key, value) -> {
            if(Boolean.TRUE.equals(MapUtil.getBool(value, Constants.GENERATE,true))){
                tableNameSet.add(key);
            }
        });
        return listTablesWithColumns(cfg.getDbConfig().getDatasourceUrl(),cfg.getDbConfig().getUsername(),cfg.getDbConfig().getPassword(),cfg.getSchema(),tableNameSet);
    }
    /**
     * 查询所有[表],包括字段
     */
    @Override
    public List<Table> listTablesWithColumns(String url,String userName,String password,String schema,List<String> generateTables) {
        DataSource dataSource =new SimpleDataSource(url,userName,password);

        List<Table> tables = new ArrayList<>();
        List<String> tableNames = MetaUtil.getTables(dataSource, schema, TableType.TABLE);
        if(null!=generateTables && !generateTables.isEmpty()){
            tableNames.retainAll(generateTables);
        }
        for (String tableName : tableNames) {
            Table sqlTable = new Table();
            cn.hutool.db.meta.Table table = MetaUtil.getTableMeta(dataSource, tableName);
            sqlTable.setTableName(tableName);
            sqlTable.setRemarks(table.getComment());
            sqlTable.setPkNames(table.getPkNames());
            sqlTable.setColumns(new ArrayList<>());
            sqlTable.setPkColumns(new ArrayList<>());
            Collection<Column> columns = table.getColumns();
            if (CollUtil.isNotEmpty(columns)) {
                int i = 0;
                for (Column column : columns) {
                    i++;
                    TableColumn tableColumn = new TableColumn();
                    tableColumn.setTableName(tableName);
                    tableColumn.setColumnName(column.getName());
                    tableColumn.setColumnType(column.getType());
                    tableColumn.setColumnTypeName(DataTypeEnum.tranceDBType(column.getTypeName()));
                    tableColumn.setRemarks(column.getComment());
                    tableColumn.setSize(column.getSize());
                    tableColumn.setIsNullable(column.isNullable());
                    tableColumn.setSortOrder(i);
                    tableColumn.setAutoIncrement(column.isAutoIncrement());
                    tableColumn.setPk(column.isPk());
                    log.debug("字段信息  SqlTableColumn:{}", tableColumn);

                    sqlTable.getColumns().add(tableColumn);
                    if(tableColumn.isPk()){
                        sqlTable.getPkColumns().add(tableColumn);
                    }
                }
            }
            tables.add(sqlTable);
        }

        return tables;
    }
}